/**
 * flip动画封装
 * @param els dom集合
 * @param option 配置项
 */
function FlipAnimation(
  els,
  option = {
    duration: 300,
    easing: 'cubic-bezier(0.33, 1, 0.68, 1)',
  }
) {
  this.elements = els;
  this.firstPosition = [];
  this.lastPosition = [];
  this.option = option;
  this.first();
}

FlipAnimation.prototype.first = function () {
  this.firstPosition = this.getPosition();
};

FlipAnimation.prototype.last = function () {
  this.lastPosition = this.getPosition();
};

// 获取记录点位置
FlipAnimation.prototype.getPosition = function () {
  return this.elements.map(item => item.getBoundingClientRect());
};

FlipAnimation.prototype.invert = function () {
  const diffPosition = this.firstPosition.map((item, index) => {
    const lastItem = this.lastPosition[index];
    return {
      left: item.left - lastItem.left,
      top: item.top - lastItem.top,
      width: item.width / lastItem.width,
      height: item.height / lastItem.height,
    };
  });

  const elList = this.elements;
  for (let i = 0; i < elList.length; i++) {
    const { left, top, width, height } = diffPosition[i];
    const el = elList[i];
    el.style.transition = 'none';
    el.style.transform = `translate3d(${left}px, ${top}px, 0px) scale(${width}, ${height})`;

    setTimeout(() => {
      el.style.transition = 'all .3s';
      el.style.transform = '';
    }, 0);
  }
};

FlipAnimation.prototype.play = function (fn) {
  fn && fn();
  this.last();
  this.invert();
};

export default FlipAnimation;